/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "app_fatfs.h"
#include "i2c.h"
#include "rtc.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "drv_w25qxx.h"
#include "bsp_crc.h"
#include "GitVersion.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define BUFSIZE 16
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
FATFS fs;
FIL file;
FIL *pf = &file;
FRESULT f_res;
UINT fnum;
BYTE work[4096];

char USER_Path[4];

RTC_DateTypeDef Data;  //???????
RTC_TimeTypeDef Time;   //???????

fifo_Handle fifo[BUFSIZE];
uint8_t fifo_tick=0,fifo_tick_buf=0;
uint8_t usart_dma_buf[128];
uint8_t mood=0;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
BYTE ReadBuffer[1024]={0};

void mount_disk(void)
{
  BYTE WriteBuffer[128]={0};
  char filename[20]={0};
  uint8_t len = 0;

  f_res = f_mount(&fs, USER_Path, 0);

  /* Get the RTC current Time */
  HAL_RTC_GetTime(&hrtc, &Time, RTC_FORMAT_BIN);
  /* Get the RTC current Date */
  HAL_RTC_GetDate(&hrtc, &Data, RTC_FORMAT_BIN);

  /* Display date Format : yy/mm/dd hh:mm:ss*/
  len=sprintf(WriteBuffer,"\n\n%02d/%02d,%02d:%02d:%02d,start,GitVersion:%s,,GitDate:%s\n", Data.Month, Data.Date,Time.Hours, Time.Minutes, Time.Seconds,GIT_VERSION,GIT_DATE);
  //Data.Year+2000
  sprintf(filename,"%02d%02d.csv", Data.Month, Data.Date);
  f_res = f_open(pf, filename, FA_OPEN_APPEND | FA_WRITE);
  f_res = f_write(&file, WriteBuffer, len, &fnum);
  f_res = f_close(pf);
}

void log_write(char* adr,RTC_DateTypeDef Data,RTC_TimeTypeDef Time,uint32_t tick)
{
  BYTE WriteBuffer[256]={0};
  char filename[20]={0};
  uint8_t len = 0;
  static FRESULT file_status = 0;

  /* Display date Format : yy/mm/dd hh:mm:ss*/
  len=sprintf(WriteBuffer,"%02d/%02d,%02d:%02d:%02d,%6d,%s\n",Data.Month, Data.Date,Time.Hours, Time.Minutes, Time.Seconds,tick,adr);
  // __disable_irq();
  
  sprintf(filename,"%02d%02d.csv", Data.Month, Data.Date);
  f_res = f_open(pf, filename, FA_OPEN_APPEND | FA_WRITE);
  f_res = f_write(&file, WriteBuffer, len, &fnum);
  file_status = f_res;
  f_res = f_close(&file);
  // if(FR_OK == file_status){ LED1_ON();}
  // else{ LED1_OFF();}
  // __enable_irq();
}

void format_disk(void)
{
  f_res = f_mkfs(USER_Path, FM_FAT, 4096, work, sizeof(work));
}

void read_file(void)
{
  f_res = f_open(&file, "config.txt", FA_READ);
  f_res = f_read(&file, ReadBuffer, sizeof(ReadBuffer), &fnum);
  f_res = f_close(&file);
}

uint8_t fileSystemInit()
{
  uint8_t res = FR_OK;
  res = f_mount(&fs, USER_Path, 1);
  if (res != FR_OK)
  {
    //No Disk file system,format disk !
    res = f_mkfs(USER_Path, FM_FAT, 4096, work, sizeof work);
    if (res == FR_OK)
    {
      res = f_mount(&fs, USER_Path, 1);
      if (res == 0)
      {
        return FR_OK;
      }
      else
        return FR_DISK_ERR;
    }
    else
      return FR_DISK_ERR;
  }
  else
    return FR_OK;
}
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/**
  * @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */

  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */
  #if 0
  extern DMA_HandleTypeDef hdma_usart1_rx;
    uint16_t i;
    if(RESET != __HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE))
    {
        uint16_t UART1_len;
        HAL_UART_DMAStop(&huart1);
        __HAL_UART_CLEAR_IDLEFLAG(&huart1);
        UART1_len = 128 - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
      if (UART1_len>4&&UART1_len<127) {
        if (fifo_tick!=fifo_tick_buf-16)fifo_tick=fifo_tick+16;
        HAL_RTC_GetTime(&hrtc, &fifo[fifo_tick/16].Time, RTC_FORMAT_BIN);
        HAL_RTC_GetDate(&hrtc, &fifo[fifo_tick/16].Data, RTC_FORMAT_BIN);
        fifo[fifo_tick/16].tick=TIM2->CNT;
        usart_dma_buf[UART1_len]=0;
        if(usart_dma_buf[0]==0xAC)sprintf(fifo[fifo_tick/16].deta,"CRC ERR,%s",(char*)usart_dma_buf);
        else sprintf(fifo[fifo_tick/16].deta,"Head ERR,%s",(char*)usart_dma_buf);
        LED1_OFF();
        if(Verify_CRC8_Check_Sum(usart_dma_buf,3)){
          if(Verify_CRC16_Check_Sum(usart_dma_buf,usart_dma_buf[1])){
            sprintf(fifo[fifo_tick/16].deta,"OK,%s",(char*)&usart_dma_buf[3]);
            LED1_ON();
          }
        }
      }
      HAL_UART_Receive_DMA(&huart1,usart_dma_buf,128);
    }
    #endif
  /* USER CODE END USART1_IRQn 1 */
}


/**
  * @brief This function handles USART3 global interrupt / USART3 wake-up interrupt through EXTI line 28.
  */
void USART3_IRQHandler(void)
{
  /* USER CODE BEGIN USART3_IRQn 0 */

  /* USER CODE END USART3_IRQn 0 */
  HAL_UART_IRQHandler(&huart3);
  /* USER CODE BEGIN USART3_IRQn 1 */
  extern DMA_HandleTypeDef hdma_usart3_rx;
    uint16_t i;
    if(RESET != __HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE))
    {
        uint16_t UART1_len;
        HAL_UART_DMAStop(&huart3);
        __HAL_UART_CLEAR_IDLEFLAG(&huart3);
        UART1_len = 128 - __HAL_DMA_GET_COUNTER(&hdma_usart3_rx);
      if (UART1_len>4&&UART1_len<127) {
        if (fifo_tick!=fifo_tick_buf-16)fifo_tick=fifo_tick+16;
        HAL_RTC_GetTime(&hrtc, &fifo[fifo_tick/16].Time, RTC_FORMAT_BIN);
        HAL_RTC_GetDate(&hrtc, &fifo[fifo_tick/16].Data, RTC_FORMAT_BIN);
        fifo[fifo_tick/16].tick=TIM2->CNT/1000;
        TIM2->CNT = 0;
        usart_dma_buf[UART1_len]=0;
        if(usart_dma_buf[0]==0xAC)sprintf(fifo[fifo_tick/16].deta,"CRC ERR,%s",(char*)usart_dma_buf);
        else sprintf(fifo[fifo_tick/16].deta,"Head ERR,%s",(char*)usart_dma_buf);
        LED2_ON();
        if(Verify_CRC8_Check_Sum(usart_dma_buf,3)){
          if(Verify_CRC16_Check_Sum(usart_dma_buf,usart_dma_buf[1])){
            sprintf(fifo[fifo_tick/16].deta,"OK,%s",(char*)&usart_dma_buf[3]);
            LED2_OFF();
          }
        }
      }
      HAL_UART_Receive_DMA(&huart3,usart_dma_buf,128);
    }
  /* USER CODE END USART3_IRQn 1 */
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */
  uint16_t TIM_CNT_tmp = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_RTC_Init();
  MX_TIM4_Init();
  MX_SPI1_Init();
  MX_SPI3_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  if (MX_FATFS_Init() != APP_OK) {
    Error_Handler();
  }
  MX_USB_Device_Init();
  MX_TIM2_Init();
  MX_USART3_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start(&htim2);
  __HAL_UART_ENABLE_IT(&huart3,UART_IT_IDLE);
  HAL_UART_Receive_DMA(&huart3,usart_dma_buf,128);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    if (mood==0) {
      LED2_OFF();
      if(HAL_GPIO_ReadPin(LED1_GPIO_Port,LED1_Pin) == SET && TIM_CNT_tmp == 0)
      {
        TIM_CNT_tmp = TIM2->CNT;
      }
      else if(HAL_GPIO_ReadPin(LED1_GPIO_Port,LED1_Pin) == SET)
      {
        if((TIM_CNT_tmp + 1000000) <  TIM2->CNT)
        {
          LED1_ON();
          TIM_CNT_tmp = 0;
        }
      }

      while(fifo_tick_buf!=fifo_tick){
        HAL_GPIO_TogglePin(LED1_GPIO_Port,LED1_Pin);
        fifo_tick_buf=fifo_tick_buf+16;
        char str[128];
        uint8_t str_len=sprintf(str,"rx:%s",(char*)fifo[fifo_tick_buf/16].deta);
        HAL_UART_Transmit_DMA(&huart3,str,str_len);
        log_write(fifo[fifo_tick_buf/16].deta,fifo[fifo_tick_buf/16].Data,fifo[fifo_tick_buf/16].Time,fifo[fifo_tick_buf/16].tick);
      }//*/
      if (HAL_GPIO_ReadPin(key1_GPIO_Port,key1_Pin)==GPIO_PIN_SET)mood=1;
      if (HAL_GPIO_ReadPin(key4_GPIO_Port,key4_Pin)==GPIO_PIN_RESET)mood=1;
    }else if(mood==1) {
      LED1_OFF();
      LED2_ON();
      __HAL_UART_DISABLE_IT(&huart3,UART_IT_IDLE);
      HAL_UART_DMAStop(&huart3);
      f_res = f_close(pf);
      MX_USB_Device_Init();
      mood=2;
    }
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Configure LSE Drive Capability
  */
  HAL_PWR_EnableBkUpAccess();
  __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48|RCC_OSCILLATORTYPE_HSE
                              |RCC_OSCILLATORTYPE_LSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  RCC_OscInitStruct.PLL.PLLN = 85;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV6;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM17 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM17)
  {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
